
package com.dg.acb.utils.ipcclient;

import java.io.Closeable;
import com.dg.acb.utils.task.NBExecutor;
import android.content.Context;
import android.os.RemoteException;

public class IPCClient<T> implements StatuMonitor<T>, Closeable {
    private final ConnectionManager<T> mConnManager;
    private final NBExecutor mNBExecutor;

    public IPCClient(Context context, IServiceHandler<T> handler) {
        mConnManager = new ConnectionManagerIml<T>(context, handler, this);
        mNBExecutor = NBExecutor.newSinglePool();
    }

    final ConnectionManager<T> getConnectionManager() {
        return mConnManager;
    }

    public void connect() {
        try {
            mConnManager.getService();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * @hide
     * @return
     * @throws RemoteException
     */
    public final T getService() throws RemoteException{
        return mConnManager.getService();
    }

    public void onRemoteExceptionOccurred(RemoteException e) {
        android.util.Log.e("IPCClient", "remote service exception, closing service");
        mConnManager.close();
        e.printStackTrace();
    }

    /**
     * close remote connection
     */
    @Override
    public void close() {
        mNBExecutor.shutdown();
        mConnManager.close();
    }

    @Override
    protected void finalize() throws Throwable {
        mConnManager.close();
        super.finalize();
    }

    protected void summitTask(Runnable run) {
        mNBExecutor.execute(run);;
    }

    @Override
    public void onServiceConnected(T service) {
    }

    @Override
    public void onServiceDisconnected() {
    }
}